from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

from src.broadcast import websocket_connections
from src.log import SCRIPTP


app = FastAPI(title="同声传译Web服务")

# 配置模板目录
templates = Jinja2Templates(directory=str(SCRIPTP.joinpath("templates")))
# 配置静态文件目录
app.mount("/static", StaticFiles(directory=str(SCRIPTP.joinpath("templates", "static"))), name="static")


@app.get("/note", response_class=HTMLResponse)
async def get_note_page(request: Request):
    return templates.TemplateResponse("note.html", {"request": request})


@app.get("/meeting", response_class=HTMLResponse)
async def get_meeting_page(request: Request, id: str):
    # 先检查会议是否存在
    if not SCRIPTP.joinpath("meeting_id").is_file() or SCRIPTP.joinpath("meeting_id").read_text() != id:
        return templates.TemplateResponse("no_meeting.html", {"request": request})
    return templates.TemplateResponse("meeting.html", {"request": request, "meeting_id": id})


@app.websocket("/ws/{meeting_id}/{language}")
async def websocket_endpoint(websocket: WebSocket, meeting_id: str, language: str):
    await websocket.accept()
    
    # 初始化连接存储
    if meeting_id not in websocket_connections:
        websocket_connections[meeting_id] = {}
    if language not in websocket_connections[meeting_id]:
        websocket_connections[meeting_id][language] = []
    
    # 添加新连接
    websocket_connections[meeting_id][language].append(websocket)
    
    try:
        while True:
            # 保持连接，不需要处理客户端消息
            await websocket.receive_text()
    except WebSocketDisconnect:
        # 移除断开的连接
        websocket_connections[meeting_id][language].remove(websocket)
        print(f"WebSocket连接已断开: {meeting_id}, {language}")


def getNeedTranslationLanguages(meeting_id: str) -> list:
    if meeting_id not in websocket_connections:
        return []
    return list(websocket_connections[meeting_id].keys())
